#!/bin/bash
################### 自动化安装mysql5.7脚本 #####################
# 执行之前：
# 	1. 去除特殊字符：sed -i 's/\r//' install_mysql57.sh
# 	2. 添加执行权限：chmod +x install_mysql57.sh
# 	3. 如果下载速度比较慢，可以提前将以下安装包上传到/opt/soft目录下：mysql-5.7.42-linux-glibc2.12-x86_64.tar.gz
	4. 检查是否已经安装了mysql：rpm -qa | grep mysql，如果已经安装过mysql，可以删除：rpm -e 文件名
# 执行命令：./install_mysql57.sh
# 执行之后：在安装过程中，会自动为root用户生成一个随机密码，需要手动修改root用户的随机密码为自己设定的密码，方法如下：
#		查看生成的随机密码：cat /usr/local/mysql/data/mysql.err
#		进入mysql的bin：cd /usr/local/mysql/bin
#		登录root用户：./mysql -uroot -p
#		输入上面的随机密码
#		# alter user user() identified by "你的密码";
#		alter user user() identified by "123456"; 
#		# 生效：
#		flush privileges;
#		修改root用户访问权限
#		use mysql;
#		update user set Host='%' where User='root';
#		flush privileges;
# 脚本说明：
########################################################

echo "----------0.准备环境----------------"
echo "准备环境OK"

echo "----------1.安装mysql5.7----------------"
cd /opt/soft
# 如果下载比较慢，也可以提前上传安装包到/opt/soft，然后将该行命令注释掉
#wget http://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-5.7.42-linux-glibc2.12-x86_64.tar.gz
FILE_PATH=/opt/soft/mysql-5.7.42-linux-glibc2.12-x86_64.tar.gz
if [ -e $FILE_PATH ]; then
    echo "$FILE_PATH存在"
else
    echo "$FILE_PATH不存在"
    exit 1
fi
# 解压
tar -zxvf mysql-5.7.42-linux-glibc2.12-x86_64.tar.gz
# 重命名
mv mysql-5.7.42-linux-glibc2.12-x86_64 mysql5.7
# 拷贝到指定目录
cp -r mysql5.7 /usr/local
cd /usr/local
mv mysql5.7 mysql
# 创建存放数据的目录data
cd /usr/local/mysql
mkdir data
chmod -R 777 /usr/local/mysql/data
# 添加mysql用户组和用户名
groupadd mysql
useradd -d /var/lib/mysql -s /sbin/nologin -g mysql mysql
# 修改mysql目录所属人
cd /usr/local
chown -R mysql:mysql mysql/
# 创建软连接
ln -s /usr/local/mysql/support-files/mysql.server /etc/init.d/mysql
ln -s /usr/local/mysql/bin/mysql /usr/bin/mysql
# 创建日志文件目录
mkdir /var/log/mariadb
touch /var/log/mariadb/mariadb.log
chown -R mysql:mysql /var/log/mariadb/
echo "install mysql5.7 success!"

echo "----------2.编辑mysql配置文件----------------"
touch /etc/my.cnf
cat >> /etc/my.cnf << EOF
[mysqld]
bind-address=0.0.0.0
port=3306
user=mysql
basedir=/usr/local/mysql
datadir=/usr/local/mysql/data
socket=/tmp/mysql.sock
log-error=/usr/local/mysql/data/mysql.err
pid-file=/usr/local/mysql/data/mysql.pid
#character config
character_set_server=utf8mb4
symbolic-links=0
explicit_defaults_for_timestamp=true
EOF
echo "edit config file success!"

echo "----------3.初始化mysql----------------"
cd /usr/local/mysql/bin
./mysqld --initialize --user=mysql --basedir=/usr/local/mysql/ --datadir=/usr/local/mysql/data/
echo "init mysql success!"

echo "----------4.启动mysql----------------"
service mysql start
echo "start mysql success!"

# 打印随机密码（后面修改root用户密码用到）
cat /usr/local/mysql/data/mysql.err